import requests
from loguru import logger
import time
import random
import sys
from work.new_recaptcha import getTaskResult

def get_time():
    time.sleep(random.randint(1, 3))

def get_cookies():
    headers = {
        "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
        "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
        "cache-control": "no-cache",
        "pragma": "no-cache",
        "priority": "u=0, i",
        "referer": "https://online.seranking.com/admin.session.lock.html",
        "sec-ch-ua": "\"Microsoft Edge\";v=\"125\", \"Chromium\";v=\"125\", \"Not.A/Brand\";v=\"24\"",
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": "\"Windows\"",
        "sec-fetch-dest": "document",
        "sec-fetch-mode": "navigate",
        "sec-fetch-site": "same-origin",
        "sec-fetch-user": "?1",
        "upgrade-insecure-requests": "1",
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36 Edg/125.0.0.0"
    }
    url = "https://online.seranking.com/login.html"
    retry_count = 0
    while retry_count < 3:
        try:
            res = requests.get(url, headers=headers, timeout=5)
        except Exception as e:
            logger.error(f"获取cookies信息请求超时，正在重新连接")
            retry_count += 1
            get_time()
            continue
        if res.status_code == 200:
            res_cookies = {}
            res_cookies.update(res.cookies)
            res_cookies['_sid'] = str(int(time.time()))
            return res_cookies
        else:
            logger.error(f"请求失败 -----> {res.status_code}")
            sys.exit()

def get_FP(cookies):
    headers = {
        "accept": "*/*",
        "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
        "cache-control": "no-cache",
        "content-length": "0",
        "origin": "https://online.seranking.com",
        "pragma": "no-cache",
        "priority": "u=4, i",
        "referer": "https://online.seranking.com/",
        "sec-ch-ua": "\"Not/A)Brand\";v=\"8\", \"Chromium\";v=\"126\", \"Microsoft Edge\";v=\"126\"",
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": "\"Windows\"",
        "sec-fetch-dest": "empty",
        "sec-fetch-mode": "no-cors",
        "sec-fetch-site": "same-site",
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36 Edg/126.0.0.0"
    }
    url = "https://collector.seranking.com/g/collect"
    params = {
        "v": "2",
        "tid": "G-WT40C25WLR",
        "gtm": "45he46c0v875675692za200zb6606926",
        "_p": str(int(time.time() * 1000)),
        "gcs": "G111",
        "gcd": "13r3r3r2r5",
        "npa": "0",
        "dma": "0",
        "tag_exp": "0",
        "gdid": "dMWZhNz",
        "cid": "89612849.1718610920",
        "ecid": "2121459210",
        "ul": "zh-cn",
        "sr": "1920x1080",
        "_fplc": "0",
        "ir": "1",
        "ur": "HK",
        "uaa": "x86",
        "uab": "64",
        "uafvl": "Not%2FA)Brand;8.0.0.0|Chromium;126.0.6478.57|Microsoft%20Edge;126.0.2592.56",
        "uamb": "0",
        "uam": "",
        "uap": "Windows",
        "uapv": "10.0.0",
        "uaw": "0",
        "are": "1",
        "frm": "0",
        "pscdl": "noapi",
        "ec_mode": "c",
        "_eu": "EA",
        "sst.rnd": "520615368.1718610920",
        "sst.gse": "1",
        "sst.etld": "google.com.hk",
        "sst.gcd": "13r3r3r2r5",
        "sst.us_privacy": "1---",
        "sst.tft": "1718610916427",
        "sst.ude": "0",
        "_s": "4",
        "dl": "https://online.seranking.com/login.html?back=true&do=login",
        "sid": str(int(time.time() * 1000)),
        "sct": "1",
        "seg": "1",
        "dr": "https://online.seranking.com/login.html?back=true&do=login",
        "dt": "Login - SE Ranking",
        "en": "user_engagement",
        "ep.left_menu_expanded": "",
        "_et": "4117",
        "ep.user_data._tag_mode": "MANUAL",
        "tfd": "22606",
        "_z": "sendBeacon"
    }
    res = requests.post(url, headers=headers, cookies=cookies ,params=params)
    if res.status_code == 200:
        return res.cookies
    else:
        logger.error(f"获取fp失败 -----> {res.status_code}")
        sys.exit()

def new_fp(cookies):
    headers = {
        "accept": "*/*",
        "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
        "attribution-reporting-eligible": "trigger;navigation-source, not-event-source",
        "attribution-reporting-support": "web",
        "cache-control": "no-cache",
        "origin": "https://online.seranking.com",
        "pragma": "no-cache",
        "priority": "u=1, i",
        "referer": "https://online.seranking.com/",
        "sec-ch-ua": "\"Not/A)Brand\";v=\"8\", \"Chromium\";v=\"126\", \"Microsoft Edge\";v=\"126\"",
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": "\"Windows\"",
        "sec-fetch-dest": "empty",
        "sec-fetch-mode": "cors",
        "sec-fetch-site": "same-site",
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36 Edg/126.0.0.0"
    }

    url = "https://collector.seranking.com/g/collect"
    params = {
        "v": "2",
        "tid": "G-WT40C25WLR",
        "gtm": "45he46c0v875675692z86606926za200zb6606926",
        "_p": str(int(time.time() * 1000)),
        "gcs": "G111",
        "gcd": "13r3r3r2r5",
        "npa": "0",
        "dma": "0",
        "tag_exp": "0",
        "gdid": "dMWZhNz",
        "cid": "758788535.1718610943",
        "ecid": "1560218545",
        "ul": "zh-cn",
        "sr": "1920x1080",
        "ir": "1",
        "ur": "HK",
        "uaa": "x86",
        "uab": "64",
        "uafvl": "Not%2FA)Brand;8.0.0.0|Chromium;126.0.6478.57|Microsoft%20Edge;126.0.2592.56",
        "uamb": "0",
        "uam": "",
        "uap": "Windows",
        "uapv": "10.0.0",
        "uaw": "0",
        "are": "1",
        "frm": "0",
        "pscdl": "noapi",
        "ec_mode": "c",
        "_eu": "EA",
        "sst.rnd": "1979667208.1718610943",
        "sst.gse": "1",
        "sst.etld": "google.com.hk",
        "sst.gcd": "13r3r3r2r5",
        "sst.adr": "1",
        "sst.us_privacy": "1---",
        "sst.tft": str(int(time.time() * 1000)),
        "sst.ude": "0",
        "_s": "1",
        "dl": "https://online.seranking.com/login.html?back=true&do=login",
        "sid": str(int(time.time())),
        "sct": "1",
        "seg": "0",
        "dr": "https://online.seranking.com/login.html?back=true&do=login",
        "dt": "Login - SE Ranking",
        "en": "page_view",
        "_fv": "1",
        "_nsi": "1",
        "_ss": "2",
        "ep.left_menu_expanded": "",
        "ep.user_data._tag_mode": "MANUAL",
        "up.geo_code": "\"d256933a\"",
        "up.gemini_uniq": cookies['uniq'],
        "tfd": "5544",
        "richsstsse": ""
    }
    res = requests.get(url, headers=headers, cookies=cookies, params=params)
    if res.status_code == 200:
        return res.cookies
    else:
        logger.error(f"update efp失败")
        sys.exit()


def se_login(user):
    site_key = "6Lejfp8pAAAAAJrnJ4-oIeKBkb0KmGt_5VKgEGO_"
    site_url = "https://online.seranking.com/login.html?back=true&do=login"

    cookies = get_cookies()
    cookies.update(get_FP(cookies))
    new_cookies = new_fp(cookies)
    cookies.update(new_cookies)
    # recaptcha = recaptcha_run(site_key, site_url)
    recaptcha = getTaskResult()
    # print(recaptcha)
    headers = {
        "Host": "online.seranking.com",
        "pragma": "no-cache",
        "cache-control": "no-cache",
        "sec-ch-ua": "\"Microsoft Edge\";v=\"125\", \"Chromium\";v=\"125\", \"Not.A/Brand\";v=\"24\"",
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": "\"Windows\"",
        "upgrade-insecure-requests": "1",
        "origin": "https://online.seranking.com",
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36 Edg/125.0.0.0",
        "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
        "sec-fetch-site": "same-origin",
        "sec-fetch-mode": "navigate",
        "sec-fetch-user": "?1",
        "sec-fetch-dest": "document",
        "referer": "https://online.seranking.com/login.html?back=true&do=login",
        "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
        "priority": "u=0, i",
        "content-type": "application/x-www-form-urlencoded"
    }
    url = "https://online.seranking.com/login.html"
    params = {
        "back": "true",
        "do": "login"
    }
    data = {
        "audit_domain": "",
        "aItem[login]": user['account'],
        "aItem[password]": user['password'],
        "g-recaptcha-response": str(recaptcha),
        "aItem[keep]": "1"
    }
    retry_count = 0
    while retry_count < 3:
        try:
            res = requests.post(url, headers=headers, cookies=cookies, params=params, data=data, allow_redirects=False, timeout=5)
        except Exception as e:
            logger.error(f"登录超时，正在重新登录...")
            retry_count += 1
            get_time()
            continue
        if res.status_code == 302:
            user_cookies = {}
            user_cookies.update(cookies)
            user_cookies.update(res.cookies)
            user['cookies'] = user_cookies
            logger.success(f"{user['account']}: 登录成功")
            return user
        else:
            logger.error(f"登录失败 -----> {res.status_code}")
            sys.exit()

# user = {"account": "houjiajun@cnmqh.com", "password": "hou999$"}
# user = {"account": "python123@cc.cc", "password": "python123"}
# se_login(user)